package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 钟乐
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Resource
    IUserService userService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户，加载是否点赞了isLike
        records.forEach(blog ->{
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryBlogById(Long id) {

        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //查询blog的用户信息
        queryBlogUser(blog);
        //查询blog是否被点过赞了
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {


        UserDTO user = UserHolder.getUser();

        if (user==null){
            //用户未登陆,直接返回
            return;
        }

        Long userId = user.getId();

        //获取获取登陆用户在set的key
        String key = "blog:liked:" + blog.getId();

        //2、判断当前用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        //设置blog中的islike字段
        blog.setIsLike(score!=null);
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    //用户一点击，就会调用这个接口
    @Override
    public Result likeBlog(Long id) {

        //1、获取登陆用户
        Long userId = UserHolder.getUser().getId();

        //获取获取登陆用户在set的key
        String key = "blog:liked:" + id;

        //2、判断当前用户是否已经点赞,用户,查分数，有就是存在，没有就是不存在
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        //用户点击按钮，得到当前点赞状态，执行下面的ifelse代码
        if (score==null){
            //3、如果未点赞，可以点赞,没有点赞，会执行这段代码

            //3。1保存点赞数+1
            boolean isSuccess = update().setSql("liked = liked+1").eq("id", id).update();

            if (isSuccess) {
                //3。2保存到redis的set集合
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }

        }else{
            //4、如何已经点赞 取消点赞，点赞了执行这段代码
            //4。1数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked-1").eq("id", id).update();

            if (isSuccess) {
                //4。2把用户用Redis的set集合移除
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result likeBlogLikes(Long id) {

        String key = "blog:liked:" + id;

        //1\查询top5的点赞用户,.range查前5个,zrange默认从小到大排
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);

        if(top5 == null || top5.isEmpty()){

            return Result.fail("点赞用户为空");
        }

        //转为long,解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());

        String join = StrUtil.join(",", ids);

        //查询top5用户的信息
        List<Object> userDTOs = userService.query()
                .in("id",ids)
                .last("ORDER BY FIELD(id,"+join+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOs);
    }
    
    @Resource
    IFollowService iFollowService;

    @Override
    public Result saveBlog(Blog blog) {

        Long user = UserHolder.getUser().getId();
        blog.setUserId(user);
        boolean isSuccess = save(blog);

        if (!isSuccess) {
            return Result.fail("新增笔记失败");
        }

        //查询笔记作者的粉丝
        List<Follow> follows = iFollowService.query().eq("follow_user_id", user).list();

        //推送笔记id给粉丝
        for (Follow follow : follows) {
            //粉丝Id
            Long userId = follow.getUserId();
            String key = RedisConstants.FEED_KEY + userId;
            //粉丝去 redis  sortedset 里面 的feed:id里面取这个这个blog就行了,每个用户占一个id，里面保存zset(blogId,time)
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        //返回id
        return Result.ok();
    }

    @Resource
    IBlogService blogService;

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {

        System.out.println("max"+max+"offset"+offset);

        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;

        //2、查询收件箱 zervrangebyscore key max 0 withscores limit 0 count，默认是从小到大，这里要从大到小取
        Set<ZSetOperations.TypedTuple<String>> tuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        //元组判空用size
        if (tuples.size()==0) {
            return Result.ok();
        }

        //初始化ArrayList的长度，防止扩容影响性能
        List<Long> ids = new ArrayList<>(tuples.size());
        long minTime = 0;
        int os = 1;
        //3、解析数据 blogId,minTime,offset要算出来
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {

            ids.add(Long.valueOf(tuple.getValue()));

            long time = tuple.getScore().longValue();

            //得到最小时间的重复值,不断重置offset，一定会算到最后一个，也就是最小的那个的重复值
            if(time==minTime){
                //计算最小元素的个数
                os++;
            }else{
                //不断重置即可，最后一定会重置到最后一个最小的元素
                minTime = time;
                os = 1;
            }
        }

        String join = StrUtil.join(",", ids);

        //4、查询blog
        List<Blog> blogs = blogService.query()
                .in("id",ids)
                .last("ORDER BY FIELD(id,"+join+")").list();

        //查询点赞和用户
        for (Blog blog : blogs) {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        }

        //动态计算出 offset和minTime ,封装返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);

    }
}
